package com.ruoyi.web.asyserver;

import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;

import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.util.Base64;

public class WxSignUtil {

    @Value("${wxpay.appid}")
    private String appId;
    @Value("${wxpay.appSecret}")
    private String appSecret;
    @Value("${wxpay.mchSerialNo}")
    private String mchSerialNo;
    @Value("${wxpay.apiKey3}")
    private String apiKey3;
    @Value("${wxpay.apiKey2}")
    private String apiKey2;
    @Value("${wxpay.keyPath}")
    private String keyPath;
    @Value("${wxpay.domain}")
    private String domain;
    @Value("${wxpay.certPath}")
    private String certPath;
    @Value("${wxpay.certP12Path}")
    private String certP12Path;
    @Value("${wxpay.mchId}")
    private String mchId;


    // 获取当前秒级时间戳
    public static long getTimestamp() {
        return System.currentTimeMillis() / 1000L;
    }

    // 生成32位随机字符串
    public static String generateNonceStr() {
        String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] nonceChars = new char[32];
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < nonceChars.length; ++i) {
            nonceChars[i] = SYMBOLS.charAt(random.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    // 构造签名串
    public static String buildPreSignString(String method, String url, long timestamp, String nonce, String body) {
        return method + "\n"
                + url + "\n"
                + timestamp + "\n"
                + nonce + "\n"
                + body + "\n";
    }

    // 使用SHA256withRSA进行签名
    public static String sign(String message, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(message.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(signature.sign());
    }

    // 组装Authorization头部
    public static String buildAuthorization(String mchid, String nonceStr, long timestamp,
                                            String serialNo, String signature) {

        return  "WECHATPAY2-SHA256-RSA2048 " + "mchid=\"" + mchid + "\","
                + "nonce_str=\"" + nonceStr + "\","
                + "timestamp=\"" + timestamp + "\","
                + "serial_no=\"" + serialNo + "\","
                + "signature=\"" + signature + "\"";


    }

    // 示例调用
    public static void main(String[] args) throws Exception {
        String method = "GET";
        String urlPath = "/v3/marketing/favor/stocks/20096190/use-flow"; // 替换实际批次号
        String body = ""; // GET 请求 body 为空

        long timestamp = getTimestamp();
        String nonce = generateNonceStr();
        String preSign = buildPreSignString(method, urlPath, timestamp, nonce, body);

        // 从 PEM 文件或 keystore 加载你的商户私钥
        PrivateKey privateKey = PemUtil.loadPrivateKey(
                new FileInputStream("D:/wxpay/apiclient_key.pem"));; // <-- 请实现这个方法加载私钥

        String signature = sign(preSign, privateKey);
        String authorization = buildAuthorization("1672075158", nonce, timestamp, "3596977EB2CDA74173550CBE1097F55302C0A5B2", signature);
        System.out.println(authorization);
        // 创建 HttpClient 实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 调用封装的 GET 请求方法
            String response = WxApiCaller.sendGet(urlPath, authorization, httpClient);
            System.out.println("微信返回结果: " + response);
        }

        System.out.println("Authorization: " + authorization);
    }
}
